﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;

namespace ZSoftInstagram.UI.Web.Infrastructure.AppEvents
{                                                                                   
    public static class AppEventManager                                             
    {                                                                               
        private static List<Type> _eventTypes;                                      
        private static List<IAppEventHandler> _handlers;                            
                                                                                    
        public static void ExecuteHandlers(AppEventType eventType)                  
        {
            Handlers.Where(t => t.EventType == eventType).ForEach(h => h.Execute());
        }

        public static List<IAppEventHandler> Handlers
        {
            get
            {
                if (_handlers == null)
                {
                    _handlers = new List<IAppEventHandler>();

                    HandlerTypes.ForEach(t => _handlers.Add(Activator.CreateInstance(t) as IAppEventHandler));
                }

                return _handlers;
            }
        }

        public static List<Type> HandlerTypes
        {
            get
            {
                if (_eventTypes == null)
                {
                    Type interfaceType = typeof(IAppEventHandler);

                    _eventTypes = Assembly.GetExecutingAssembly()
                        .GetTypes()
                        .Where(t => !t.IsInterface && interfaceType.IsAssignableFrom(t))
                        .ToList();
                }

                return _eventTypes;
            }
        }
    }
}